﻿
package com.android.finaltracer;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.finaltracer.engine.EngineService;
import com.android.finaltracer.model.BindInterface;
import com.android.finaltracer.model.FTDataProvider.RelationColumns;
import com.android.finaltracer.model.FTProviderInterface;
import com.android.finaltracer.model.SettingCreator;
import com.android.finaltracer.model.UserBindInfo;

public class GetNumberActivity extends Activity {

    private ImageView add_bind_phone_iv, del_bind_phone_iv, back_iv;
    private RelativeLayout del_bind_phone_rl;
    private ListView phone_list;
    private TextView title_tv;
    private Cursor mCursor;
    private RelationNumberCursorAdapter mRelationAdapter;
    Messenger mService = null;
    private boolean mBound = false;
    private boolean isDeleteing;

    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            mService = null;
            mBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_all_number);
        phone_list = (ListView) findViewById(R.id.phone_list);

        // add hw begin
        BindInterface bindInterface = new BindInterface() {

            @Override
            public void bindReq(String phoneNum) {
                // TODO Auto-generated method stub
                if (mService == null) {
                    return;
                }
                try {
                    ContentValues value = new ContentValues();
                    value.put(RelationColumns.WEIGHT_TYPE,
                            RelationColumns.WEIGHT_TYPE_WAIT_BIND);
                    GetNumberActivity.this
                            .getContentResolver()
                            .update(Uri
                                    .parse("content://com.android.ft.provider.data/relations"),
                                    value,
                                    RelationColumns.NUMBER + "='" + phoneNum
                                            + "'", null);
                    mService.send(Message.obtain(
                            null,
                            EngineService.MSG_UI_SERVICE_BIND_PHONE_REQ,
                            new UserBindInfo(
                                    UserBindInfo.REMOTE_BIND_PHONE_REQ,
                                    phoneNum, SettingCreator.settingInit(
                                            GetNumberActivity.this)
                                            .getImeiStr())));
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        FTProviderInterface.getInstance(this).clearWaitBindSign(null);
        // add hw end
        mCursor = getAllRelationNumbers();
        mRelationAdapter = new RelationNumberCursorAdapter(this, mCursor,
                bindInterface);
        phone_list.setAdapter(mRelationAdapter);
        phone_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                // int keyID =
                // mCursor.getInt(mCursor.getColumnIndex(RelationColumns._ID));
                // if(keyID>RelationColumns.WEIGHT_TYPE_UNBIND){
                // return;
                // }
                if (!isDeleteing) {
                    return;
                }
                String phoneNumber = mCursor.getString(mCursor
                        .getColumnIndex(RelationColumns.NUMBER));
                // Intent intent = new
                // Intent(GetNumberActivity.this,ModifiyPhoneNumberActivity.class);
                // intent.putExtra(FTKey.INTENT_ACTION_KEY_PHONE_NUMBER,
                // phoneNumber);
                // startActivity(intent);
                mRelationAdapter.togglePhone(phoneNumber);
            }
        });

        phone_list.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                startDel();
                String phoneNumber = mCursor.getString(mCursor
                        .getColumnIndex(RelationColumns.NUMBER));
                mRelationAdapter.togglePhone(phoneNumber);
                return true;
            }
        });

        add_bind_phone_iv = (ImageView) findViewById(R.id.add_bind_phone_iv);
        add_bind_phone_iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                setAsocciatePhoneNum();
            }
        });
        // add hw begin 5.23
        isDeleteing = false;
        title_tv = (TextView) findViewById(R.id.title_tv);
        del_bind_phone_rl = (RelativeLayout) findViewById(R.id.del_bind_phone_rl);
        del_bind_phone_iv = (ImageView) del_bind_phone_rl
                .findViewById(R.id.del_bind_phone_iv);
        del_bind_phone_rl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Builder dialog = new AlertDialog.Builder(GetNumberActivity.this);
                dialog.setIcon(android.R.drawable.ic_dialog_info);
                dialog.setTitle("删除关联号码");
                dialog.setMessage("确认删除这些号码？");
                dialog.setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                delBindPhone(mRelationAdapter.getPhones());
                                finishDel();
                            }
                        })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        dialog.dismiss();
                                    }
                                }).create().show();
            }
        });
        back_iv = (ImageView) findViewById(R.id.back_iv);
        back_iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finishDel();
            }
        });
        if (mCursor != null && mCursor.getCount() == 0) {
            setAsocciatePhoneNum();
        }
        // add hw end 5.23
        // if (mCursor != null && mCursor.getCount() >= 5){
        // add_bind_phone_iv.setEnabled(false);
        // }else {
        // add_bind_phone_iv.setEnabled(true);
        // }
    }

    private Cursor getAllRelationNumbers() {
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        String selection = RelationColumns.WEIGHT_TYPE + ">'"
                + RelationColumns.WEIGHT_TYPE_COMMEN + "'";
        Cursor mCursor = getContentResolver().query(phoneUri, null, selection,
                null, null);
        return mCursor;
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        bindService();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        // if (mCursor != null && mCursor.getCount() >= 5){
        // add_number_btn.setEnabled(false);
        // }else {
        // add_number_btn.setEnabled(true);
        // }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCursor != null) {
            mCursor.close();
        }
        // FIXME: need to clear call sequence.
        unBindService();
    }

    private void bindService() {
        if (mBound) {
            return;
        }
        // bind service
        Intent serviceIntent = new Intent(this, EngineService.class);
        mBound = getApplicationContext().bindService(serviceIntent, mConn,
                Context.BIND_AUTO_CREATE);
        Log.i("hw", "bind service " + mBound);
    }

    private void unBindService() {
        if (!mBound) {
            return;
        }
        getApplicationContext().unbindService(mConn);
    }

    private void startDel() {
        if (isDeleteing) {
            return;
        }
        isDeleteing = true;
        add_bind_phone_iv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.right_out));
        add_bind_phone_iv.setVisibility(View.GONE);
        del_bind_phone_rl.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.down_in));
        del_bind_phone_rl.setVisibility(View.VISIBLE);
        back_iv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.left_in));
        back_iv.setVisibility(View.VISIBLE);
        title_tv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.scale_in));
        title_tv.setText(R.string.del_associated_phone_tip);
    }

    private void finishDel() {
        if (!isDeleteing) {
            return;
        }
        mRelationAdapter.clearPhones();
        isDeleteing = false;
        add_bind_phone_iv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.right_in));
        add_bind_phone_iv.setVisibility(View.VISIBLE);
        del_bind_phone_rl.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.down_out));
        del_bind_phone_rl.setVisibility(View.GONE);
        back_iv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.left_out));
        back_iv.setVisibility(View.GONE);
        title_tv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.scale_in));
        title_tv.setText(R.string.associated_phone);
    }

    private void delBindPhone(ArrayList<String> phones) {
        if (phones == null || phones.size() == 0) {
            return;
        }
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        StringBuffer sb = new StringBuffer();
        int i = 0;
        do {
            sb.append(RelationColumns.NUMBER + "='" + phones.get(i) + "'");
            if (i < phones.size() - 1) {
                sb.append(" OR ");
            }
            i++;
        } while (i < phones.size());
        getContentResolver().delete(phoneUri, sb.toString(), null);
        // RelationColumns.NUMBER+"='"+phoneNum+"'";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isDeleteing) {
                finishDel();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean insertNewPhone(String newNumber) {
        boolean result = false;
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        ContentValues values = new ContentValues();
        values.put(RelationColumns.NUMBER, newNumber);
        values.put(RelationColumns.WEIGHT_TYPE,
                RelationColumns.WEIGHT_TYPE_UNBIND);
        Uri error = getContentResolver().insert(phoneUri, values);
        result = (error == null) ? false : true;

        return result;
    }

    private boolean hasPhone(String phoneNum) {
        boolean has = false;
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        String selection = RelationColumns.NUMBER + "='" + phoneNum + "'";
        Cursor mCursor = getContentResolver().query(phoneUri, null, selection,
                null, null);
        if (mCursor != null && mCursor.getCount() > 0) {
            has = true;
        }
        if (mCursor != null) {
            mCursor.close();
        }
        return has;
    }

    private void setAsocciatePhoneNum() {
        if (mCursor != null && mCursor.getCount() >= 5) {
            Toast.makeText(GetNumberActivity.this,
                    getResources().getString(R.string.associated_phone_max),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        LayoutInflater layoutInflater = LayoutInflater
                .from(GetNumberActivity.this);
        View add_associate_phone_dialog = layoutInflater.inflate(
                R.layout.add_associate_phone_dialog, null);
        final EditText associate_phone_num_et = (EditText) add_associate_phone_dialog
                .findViewById(R.id.associate_phone_num_et);
        Builder dialog = new AlertDialog.Builder(GetNumberActivity.this);
        dialog.setIcon(android.R.drawable.ic_dialog_info);
        dialog.setTitle("设置关联号码");
        dialog.setView(add_associate_phone_dialog);
        dialog.setPositiveButton("设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String associate_phone_num = associate_phone_num_et.getText()
                        .toString();
                if (associate_phone_num == null
                        || associate_phone_num.length() == 0) {
                    // 手机号为空
                    Toast.makeText(GetNumberActivity.this, "手机号为空",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else if (!associate_phone_num.matches("1[0-9]+")) {
                    // 手机号不符合规范
                    Toast.makeText(GetNumberActivity.this, "手机号不符合规范",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else if (associate_phone_num.length() < 11) {
                    // 手机号位数不够
                    Toast.makeText(GetNumberActivity.this, "手机号位数不对",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else if (hasPhone(associate_phone_num)) {
                    Toast.makeText(GetNumberActivity.this, "该号码已存在",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                insertNewPhone(associate_phone_num);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).create().show();

        associate_phone_num_et.requestFocus();
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 200);
        // Intent intent = new Intent(GetNumberActivity.this,
        // ModifiyPhoneNumberActivity.class);
        // startActivity(intent);
    }

}
